package com.szgr.baoyin.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.PopupWindow;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.szgr.baoyin.MyApplication;
import com.szgr.baoyin.R;
import com.szgr.baoyin.adapter.StoreListAdapter;
import com.szgr.baoyin.model.Goods;
import com.szgr.baoyin.utils.Constant;
import com.szgr.baoyin.utils.MyTool;
import com.szgr.baoyin.utils.ToastUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商城
 */
public class StoreActivity extends BaseActivity implements AdapterView.OnItemClickListener, AbsListView.OnScrollListener {

    private PopupWindow popupWindow;
    private List<Goods> showData;
    private StoreListAdapter storeListAdapter;
    private ListView storeListView;
    private int currentPage = 1;
    private String key = "2";
    private String order = "1";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_store2);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initActionBar() {
        actionBarTitle.setText("商城");
        actionBarRight.setImageResource(R.drawable.car);
        actionBarRight.setVisibility(View.VISIBLE);

    }

    @Override
    protected void onResume() {
        super.onResume();
        System.out.println("----count--->" + MyApplication.getmInstance().getCartNum());
        if(MyApplication.getmInstance().getCartNum() > 0){
            actionBarCount.setVisibility(View.VISIBLE);
            actionBarCount.setText(MyApplication.getmInstance().getCartNum() + "");
        }else{
            actionBarCount.setVisibility(View.GONE);
        }
    }

    @Override
    public void initView() {
        showData = new ArrayList<>();

        storeListView = (ListView) findViewById(R.id.store_new_list_view);
        storeListAdapter = new StoreListAdapter(this, showData);
        storeListView.setAdapter(storeListAdapter);
        storeListView.setOnItemClickListener(this);
        storeListView.setOnScrollListener(this);

        findViewById(R.id.accessory_choose_type).setOnClickListener(this);
        findViewById(R.id.store_sort).setOnClickListener(this);
        findViewById(R.id.store_sale).setOnClickListener(this);

        getGoods("", key, order);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.action_bar_left:
                finish();
                break;
            case R.id.action_bar_right:
                startActivity(new Intent(this,CartActivity.class));
                break;
            case R.id.accessory_choose_type:

                break;
            case R.id.store_sort:
                if(showData.size() > 0) {
                    showPopupWindow(v);
                }
                break;
            case R.id.store_sale:
                break;
            case R.id.out:
                popupWindow.dismiss();
                popupWindow = null;
                break;
        }
    }

    private void showPopupWindow(View view1) {
        if(popupWindow != null && popupWindow.isShowing()){
            popupWindow.dismiss();
            popupWindow = null;
        }else {
            View view = LayoutInflater.from(this).inflate(R.layout.layout_store_filter, null);
            view.findViewById(R.id.out).setOnClickListener(this);

            view.measure(0, 0);
            popupWindow = new PopupWindow(view, MyTool.getScreenWidth(getWindowManager()),MyTool.getScreenHeight(getWindowManager()));
            popupWindow.showAsDropDown(view1);
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent storeIntent = new Intent(this,StoreDeatilActivity.class);
        storeIntent.putExtra("goods_id", showData.get(position).getGoods_id());
        startActivity(storeIntent);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
            popupWindow = null;
        }
    }

    /**
     * 获取商品
     */
    private void getGoods(final String gc_id, final String key, final String order) {
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_GET_GOODS,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        System.out.println("----->" + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            String code = jsonObject.getString("code");
                            if("200".equals(code) && jsonObject.has("datas")){
                                JSONObject datas = jsonObject.getJSONObject("datas");
                                JSONArray goods_list = datas.getJSONArray("goods_list");
                                Gson gson = new Gson();
                                List<Goods> data = (List<Goods>)gson.fromJson(goods_list.toString(), new TypeToken<List<Goods>>() {
                                }.getType());
                                if(data.size() == 0){
                                    ToastUtils.showToast("没有更多商品了");
                                }
                                showData.addAll(data);
                                storeListAdapter.setData(showData);
                                currentPage ++ ;
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
//                map.put("store_id","");
//                map.put("goods_name","vmc");
                map.put("gc_id",gc_id);
//                map.put("gc_deep","1");
//                map.put("min_price",minPrice + "");
//                map.put("max_price",maxPrice + "");
//                map.put("goods_state","1");
                map.put("key",key);
                map.put("order",order);
                map.put("page",currentPage + "");
                map.put("pagesize",Constant.PAGE_SIZE + "");
//                map.put("imgsize",Constant.IMG_SIZE + "");
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(sr);
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        if(scrollState == SCROLL_STATE_IDLE){
            if(storeListView.getLastVisiblePosition() == storeListView.getCount() - 1) {
                getGoods("",key,order);
            }
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

    }
}
